<template>
  <div class="pay-order">
    <!-- 头部导航 -->
    <div class="header">
      <div class="back-btn" @click="goBack">‹</div>
      <div class="title">确认订单</div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 电影信息卡片 -->
      <div class="movie-card">
        <div class="movie-poster">
          <img
            :src="resultData.filmImg"
            alt="暂无图片">
        </div>
        <div class="movie-info">
          <div class="movie-title">{{resultData.filmName}}</div>
          <div class="movie-time">{{formatScheduleDate}} {{resultData.startTime}}-{{resultData.endTime}}</div>
          <div class="cinema-name">{{resultData.cinemaName}}</div>
          <div class="seat-info">{{resultData.playHall}}号厅 {{formatSeats}}</div>
          <div class="ticket-info">
            <span class="ticket-count">{{selectedSeats.length}}张</span>
            <span class="original-price">原价 ¥ {{resultData.price}}</span>
          </div>
        </div>
        <div class="countdown">
          <div class="time-icon">⏰</div>
          <div class="time">{{formatCountdown}}</div>
        </div>
      </div>

      <!-- 退改签政策 -->
      <div class="policies">
        <div class="policy-item">
          <div class="policy-icon success">✓</div>
          <span>限时退票</span>
        </div>
        <div class="policy-item">
          <div class="policy-icon success">✓</div>
          <span>限时改签</span>
        </div>
        <div class="policy-link">
          <span>查看详情</span>
          <span class="arrow">›</span>
        </div>
      </div>

      <!-- 观影小吃 -->
      <div class="snacks-section">
        <div class="section-header">
          <h3>观影小吃</h3>
          <div class="view-all">
            <span>查看全部</span>
            <span class="arrow">›</span>
          </div>
        </div>

        <!-- 优惠券 -->
        <div class="coupon-item">
          <div class="coupon-price">¥2</div>
          <div class="coupon-desc">20元以上可用</div>
          <div class="coupon-action">领取</div>
        </div>

        <!-- 小吃商品 -->
        <div class="snack-item" v-for="item in resultData.streetFoodList" :key="item.id">
          <div class="snack-image">
            <img
            :src="item.imgUrl"
            alt="暂无图片">
          </div>
          <div class="snack-info">
            <div class="snack-name">单人餐｜{{item.name}}</div>
            <div class="snack-price">
              <span class="current-price">¥ {{item.currentPrice}}</span>
              <span class="original-price">¥ {{item.originalPrice}}</span>
            </div>
          </div>
          <div class="quantity-controls">
            <div class="minus-btn" @click="removeSnack(item)" v-show="getSnackQuantity(item.id) > 0">-</div>
            <span class="quantity" v-show="getSnackQuantity(item.id) > 0">{{ getSnackQuantity(item.id) }}</span>
            <div class="add-btn" @click="addSnack(item)">+</div>
          </div>
        </div>

      </div>
    </div>

    <!-- 底部支付区域 -->
    <div class="payment-section">
      <div class="payment-info">
        <div class="total-price">¥ {{totalPrice}}</div>
        <div class="price-detail" @click="showOrderDetail = true">明细 ^</div>
      </div>
      <button class="pay-btn" @click="toPay">确认支付</button>
    </div>

    <!-- 订单明细弹窗 -->
    <div v-if="showOrderDetail" class="detail-modal" @click="closeDetailModal">
      <div class="detail-content" @click.stop>
        <div class="detail-header">
          <h3>订单明细</h3>
          <button class="close-btn" @click="closeDetailModal">×</button>
        </div>
        <div class="detail-body">
          <!-- 电影票 -->
          <div class="detail-item">
            <div class="item-name">电影票</div>
            <div class="item-detail">
              <span>¥{{resultData.price}} × {{selectedSeats.length}}张</span>
              <span class="item-total">¥{{ticketTotalPrice}}</span>
            </div>
          </div>
          
          <!-- 小吃列表 -->
          <div class="detail-item" v-for="snack in selectedSnacks" :key="snack.id">
            <div class="item-name">{{snack.name}}</div>
            <div class="item-detail">
              <span>¥{{snack.currentPrice}} × {{snack.quantity}}份</span>
              <span class="item-total">¥{{(snack.currentPrice * snack.quantity).toFixed(2)}}</span>
            </div>
          </div>
          
          <div class="detail-total">
            <div class="total-row">
              <span>总计</span>
              <span class="total-amount">¥{{totalPrice}}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 二维码支付弹窗 -->
    <div v-if="showQrCode" class="qr-modal" @click="closeQrModal">
      <div class="qr-content" @click.stop>
        <div class="qr-header">
          <h3>扫码支付</h3>
          <button class="close-btn" @click="closeQrModal">×</button>
        </div>
        <div class="qr-body">
          <div class="qr-code-container">
            <img v-if="qrCodeText" :src="qrCodeImage" alt="支付二维码" @error="handleQrError" />
            <div v-else class="qr-loading">生成二维码中...</div>
          </div>
          <p class="qr-tip">请使用支付宝扫描上方二维码完成支付</p>
          <div class="order-info">
            <p>订单号：{{ orderInfo.orderNo }}</p>
            <p>支付金额：¥{{ totalPrice }}</p>
          </div>
          <button class="payment-check-btn" @click="checkPaymentStatus">已完成支付</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, getCurrentInstance } from 'vue'
import api from '@/utils/http'
import { ElMessage } from 'element-plus'

const global=getCurrentInstance().appContext.config.globalProperties;

const resultData = ref({})
const selectedSeats = ref([])
const selectedSnacks = ref([]) // 选中的小吃
const showOrderDetail = ref(false) // 订单明细弹窗

// 倒计时相关
const countdownTime = ref(10 * 60) // 10分钟，单位：秒
const countdownTimer = ref(null)

// 二维码相关
const showQrCode = ref(false)
const qrCodeText = ref('')
const orderInfo = ref({})


// 格式化排片日期显示
const formatScheduleDate = computed(() => {
  if (!resultData.value.sliceArrangementDate) {
    return '今天'
  }
  
  const scheduleDate = new Date(resultData.value.sliceArrangementDate)
  const today = new Date()
  
  today.setHours(0, 0, 0, 0)
  scheduleDate.setHours(0, 0, 0, 0)
  
  const diffTime = scheduleDate.getTime() - today.getTime()
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  const month = scheduleDate.getMonth() + 1
  const day = scheduleDate.getDate()
  
  if (diffDays === 0) {
    return `今天 ${month}月${day}日`
  } else if (diffDays === 1) {
    return `明天 ${month}月${day}日`
  } else if (diffDays === 2) {
    return `后天 ${month}月${day}日`
  } else if (diffDays > 0) {
    return `${month}月${day}日`
  } else {
    return `${month}月${day}日`
  }
})

// 格式化座位显示
const formatSeats = computed(() => {
  return selectedSeats.value.map(seat => {
    const [row, seatNum] = seat.split('-')
    return `${row}排${seatNum}座`
  }).join(' ')
})

// 电影票总价
const ticketTotalPrice = computed(() => {
  const price = resultData.value.price || 0
  const seatCount = selectedSeats.value.length
  return price * seatCount
})

// 小吃总价
const snackTotalPrice = computed(() => {
  return selectedSnacks.value.reduce((total, snack) => {
    return total + (snack.currentPrice * snack.quantity)
  }, 0)
})

// 总价计算
const totalPrice = computed(() => {
  return (ticketTotalPrice.value + snackTotalPrice.value).toFixed(2)
})

// 格式化倒计时显示
const formatCountdown = computed(() => {
  const minutes = Math.floor(countdownTime.value / 60)
  const seconds = countdownTime.value % 60
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
})

// 生成二维码图片URL
const qrCodeImage = computed(() => {
  if (!qrCodeText.value) return ''
  // 使用在线二维码生成API
  return `https://api.isoyu.com/qr/?m=0&e=L&p=10&url=${encodeURIComponent(qrCodeText.value)}`
})

// 开始倒计时
const startCountdown = () => {
  countdownTimer.value = setInterval(() => {
    countdownTime.value--
    
    if (countdownTime.value <= 0) {
      clearInterval(countdownTimer.value)
      alert('支付超时，请重新选择座位')
      goBack()
    }
  }, 1000)
}

// 停止倒计时
const stopCountdown = () => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
    countdownTimer.value = null
  }
}

// 返回上一页
const goBack = () => {
  stopCountdown()
  global.$router.back()
}

// 获取小吃数量
const getSnackQuantity = (snackId) => {
  const snack = selectedSnacks.value.find(s => s.id === snackId)
  return snack ? snack.quantity : 0
}

// 添加小吃
const addSnack = (item) => {
  const existingSnack = selectedSnacks.value.find(s => s.id === item.id)
  if (existingSnack) {
    existingSnack.quantity++
  } else {
    selectedSnacks.value.push({
      id: item.id,
      name: item.name,
      currentPrice: item.currentPrice,
      originalPrice: item.originalPrice,
      quantity: 1
    })
  }
}

// 删除小吃
const removeSnack = (item) => {
  const existingSnack = selectedSnacks.value.find(s => s.id === item.id)
  if (existingSnack) {
    existingSnack.quantity--
    if (existingSnack.quantity <= 0) {
      const index = selectedSnacks.value.indexOf(existingSnack)
      selectedSnacks.value.splice(index, 1)
    }
  }
}

// 关闭订单明细弹窗
const closeDetailModal = () => {
  showOrderDetail.value = false
}

// 关闭二维码弹窗
const closeQrModal = () => {
  showQrCode.value = false
  startCountdown()
}

const handleQrError = () => {
  console.error('二维码加载失败')
}

// 检查支付状态
const checkPaymentStatus = async () => {
  if (!orderInfo.value.orderNo) {
    alert('订单号不存在')
    return
  }
  
  try {
    const response = await api.get(`/orders/getOrderNo/${orderInfo.value.orderNo}`)
    if (response.data) {
      if (response.data.status === 1) {
        ElMessage.success('支付成功!')
        closeQrModal()
        global.$router.push('/orderView')
      } else {
        ElMessage.warning('您未支付')
      }
    }
  } catch (error) {
    console.error('检查支付状态失败:', error)
    alert('检查支付状态失败，请重试')
  }
}

const toPay = () => {
  // stopCountdown()
  // if(qrCodeText.value){
  //   showQrCode.value = true
  //   return
  // }
  
  // 构建MovieOrderDTO参数
  let userId = localStorage.getItem('userId');
  if (!userId) {
    global.$router.push({ name: 'LoginView' });
    return;
  } 
  console.log(userId,"userId");
  
  const orderData = {
    schedulingId: global.$route.query.showtimeId,
    soldSeats: selectedSeats.value.join(','),
    userId:userId,
    totalAmount: parseFloat(totalPrice.value),
    streetFoodOrderList: selectedSnacks.value.map(snack => ({
      num: snack.quantity,
      streatFoodId: snack.id, 
      price: snack.currentPrice
    }))
  }
  
  api.post('/orders/alipay', orderData).then(res => {
    if(res.data){
      orderInfo.value = res.data
      qrCodeText.value = res.data.qrCode
      showQrCode.value = true
    }
  }).catch(error => {
    console.error('支付请求失败:', error)
    alert('支付请求失败，请重试')
  })
}

onMounted(()=>{
  const showtimeId = global.$route.query.showtimeId
  selectedSeats.value = global.$route.query.seatList
  
  startCountdown()
  
  api.get('/movieScheduling/payOrder/'+showtimeId).then(res => {
    if(res.data){
      resultData.value = res.data
    }
  })
})

onUnmounted(() => {
  stopCountdown()
})

</script>

<style scoped>
.pay-order {
  background: #f5f5f5;
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12px 16px;
  background: white;
  border-bottom: 1px solid #eee;
  position: relative;
}

.back-btn {
  position: absolute;
  left: 16px;
  font-size: 24px;
  color: #333;
  cursor: pointer;
  padding: 4px;
}

.title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.actions {
  position: absolute;
  right: 16px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.menu-dots,
.location-icon {
  font-size: 18px;
  color: #333;
  cursor: pointer;
  padding: 4px;
}

.main-content {
  flex: 1;
  padding-bottom: 80px;
}

.movie-card {
  background: white;
  padding: 16px;
  margin-bottom: 8px;
  display: flex;
  gap: 12px;
}

.movie-poster {
  flex-shrink: 0;
}

.movie-poster img {
  width: 80px;
  height: 110px;
  border-radius: 8px;
  object-fit: cover;
}

.movie-info {
  flex: 1;
}

.movie-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.movie-time {
  font-size: 14px;
  color: #666;
}

.cinema-name {
  font-size: 14px;
  color: #666;
}

.seat-info {
  font-size: 14px;
  color: #666;
}

.ticket-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.ticket-count {
  font-size: 14px;
  color: #333;
}

.original-price {
  font-size: 14px;
  color: #666;
}

.countdown {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.time-icon {
  font-size: 16px;
  color: #666;
}

.time {
  font-size: 14px;
  color: #666;
}

.policies {
  background: white;
  padding: 12px 16px;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 16px;
}

.policy-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

.policy-icon {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  color: white;
}

.policy-icon.success {
  background: #52c41a;
}

.policy-item span {
  font-size: 12px;
  color: #333;
}

.policy-link {
  margin-left: auto;
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #666;
  cursor: pointer;
}

/* 观影小吃 */
.snacks-section {
  background: white;
  margin-bottom: 8px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.section-header h3 {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.view-all {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #666;
  cursor: pointer;
}

.coupon-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.coupon-price {
  font-size: 18px;
  font-weight: 600;
  color: #ff4757;
  margin-right: 8px;
}

.coupon-desc {
  font-size: 12px;
  color: #666;
  flex: 1;
}

.coupon-action {
  background: #ff4757;
  color: white;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  margin-right: 8px;
  cursor: pointer;
}

.snack-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f8f8f8;
}

.snack-item:last-child {
  border-bottom: none;
}

.snack-image {
  flex-shrink: 0;
  margin-right: 12px;
}

.snack-image img {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  object-fit: cover;
}

.snack-info {
  flex: 1;
}

.snack-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 6px;
}

.snack-price {
  display: flex;
  align-items: center;
  gap: 8px;
}

.current-price {
  font-size: 16px;
  font-weight: 600;
  color: #ff4757;
}

.snack-price .original-price {
  font-size: 12px;
  color: #999;
  text-decoration: line-through;
}

.add-btn {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  border: 1px solid #ff4757;
  color: #ff4757;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.add-btn:hover {
  background: #ff4757;
  color: white;
}

.quantity-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.minus-btn {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  border: 1px solid #ff4757;
  color: #ff4757;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.minus-btn:hover {
  background: #ff4757;
  color: white;
}

.quantity {
  font-size: 14px;
  color: #333;
  min-width: 20px;
  text-align: center;
}

/* 底部支付区域 */
.payment-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 16px;
  border-top: 1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
}

.payment-info {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.total-price {
  font-size: 20px;
  font-weight: 600;
  color: #ff4757;
}

.price-detail {
  font-size: 12px;
  color: #666;
  cursor: pointer;
}

.pay-btn {
  background: #ff4757;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 20px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: background 0.2s ease;
}

.pay-btn:hover {
  background: #ff3742;
}

.arrow {
  color: #ccc;
}

.qr-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.qr-content {
  background: white;
  border-radius: 12px;
  width: 320px;
  max-width: 90vw;
  max-height: 80vh;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.qr-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid #eee;
}

.qr-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.2s ease;
}

.close-btn:hover {
  background: #f5f5f5;
  color: #333;
}

.qr-body {
  padding: 20px;
  text-align: center;
}

.qr-code-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 16px;
  padding: 10px;
  background: #f9f9f9;
  border-radius: 8px;
  min-height: 220px;
}

.qr-code-container img {
  width: 200px;
  height: 200px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.qr-loading {
  color: #666;
  font-size: 14px;
}

.qr-tip {
  color: #666;
  font-size: 14px;
  margin: 16px 0;
  line-height: 1.4;
}

.order-info {
  background: #f8f8f8;
  padding: 12px;
  border-radius: 8px;
  margin-top: 16px;
}

.order-info p {
  margin: 6px 0;
  font-size: 14px;
  color: #333;
}

.order-info p:first-child {
  color: #666;
  font-size: 12px;
}

.order-info p:last-child {
  color: #ff4757;
  font-weight: 600;
  font-size: 16px;
}

.payment-check-btn {
  width: 100%;
  background: #ff4757;
  color: white;
  border: none;
  padding: 12px 20px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  margin-top: 20px;
  transition: all 0.2s ease;
}

.payment-check-btn:hover {
  background: #ff3742;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 71, 87, 0.3);
}

/* 订单明细弹窗 */
.detail-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.detail-content {
  background: white;
  border-radius: 12px;
  width: 320px;
  max-width: 90vw;
  max-height: 80vh;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.detail-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid #eee;
}

.detail-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.detail-body {
  padding: 20px;
  max-height: 400px;
  overflow-y: auto;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;
}

.detail-item:last-child {
  border-bottom: none;
}

.item-name {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.item-detail {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

.item-detail span:first-child {
  font-size: 12px;
  color: #666;
}

.item-total {
  font-size: 14px;
  color: #ff4757;
  font-weight: 600;
}

.detail-total {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 2px solid #ff4757;
}

.total-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-row span:first-child {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.total-amount {
  font-size: 20px;
  font-weight: 600;
  color: #ff4757;
}
</style>
